from typing import List


class ParamError(Exception):
    def __str__(self):
        return '参数范围不对'


class Student:
    """
    自己根据题目要求实现
    """
    def __init__(self, studentNo, studentName, sex):
        self.studentNo = studentNo
        self.studentName = studentName
        self.sex = sex
        self.__grade = 0

    @property
    def grade(self):
        return self.__grade

    @grade.setter
    def grade(self, new_grade):
        if 0 <= new_grade <= 100:
            self.__grade = new_grade
        else:
            raise ParamError

    def __str__(self):
        return f'学号：{self.studentNo}, 姓名：{self.studentName},性别： {self.sex}, 成绩：{self.__grade}'


class StudentList:
    def __init__(self, student_list: List[Student]):
        self.s_list = student_list

    def get(self, student_id: int):
        """
        根据 student_id 查询信息
        """
        with open('student.data', 'r', encoding='utf-8') as f:
            new_list = eval(f.read())
            self.s_list = [Student(i['studentNo'], i['studentName'], i['sex']) for i in new_list]

        for i in self.s_list:
            if student_id == i.studentNo:
                print(f'学号为{student_id}的学员信息为{i}')
                break
        else:
            print(f'学号为{student_id}的学员不存在')

    def delete(self, student_id: int):
        """
        根据 student_id 删除信息
        """
        for i in self.s_list:
            if student_id == i.studentNo:
                self.s_list.remove(i)
                print(f'成功删除学员{i.studentName}')
                break
        else:
            print(f'学号为{student_id}的学员不存在')

    def update(self, student: Student):
        if student not in self.s_list:
            print(f'学号为{student.studentNo}的学员不存在')
        else:
            student.studentNo = input('请输入学员的新学号：')
            student.studentName = input('请输入学员的新姓名：')
            student.sex = input('请输入学员的新性别：')
            student.grade = int(input('请输入学员成绩：'))
            print(f'更新后的学员信息为：{student}')

    def save(self, student: Student):
        self.s_list.append(student)
        with open('student.data', 'w', encoding='utf-8') as f:
            student_list = [i.__dict__ for i in self.s_list]
            f.write(str(student_list))


if __name__ == '__main__':
    # 入参自己定义
    s1 = Student(1, '哈哈1', '男')
    s2 = Student(2, '哈哈2', '男')
    s3 = Student(3, '哈哈3', '女')
    # 初始化一个成员名单
    s_list = StudentList([s1, s2, s3])
    # 实现save
    s4 = Student(4, '哈哈4', '女')
    s_list.save(s4)
    # 实现update
    s_list.update(s4)
    # 实现get()方法
    s_list.get(1)
    # 实现delete
    s_list.delete(1)